class CommentGradesController < ApplicationController
  
  def grade_with
    val = params[:val].to_f
    comment = params[:comment] #id
    myId = session[:user_id]
    
   #Have I already graded that comment?
   query = "Select * from comment_grades where comment_id = #{comment} and user_id = #{myId}"
   @previous_grades = CommentGrade.find_by_sql(query)
   if @previous_grades.length == 0 then
    
      #get the User with id (get user_id of user that published that comment)
      query = "Select * from users where id = (Select user_id from comments where id = #{comment});"
   
      #find comment owner
      @comment_owner = User.find_by_sql(query)[0]
      #and increment his karma
#       @comment_owner.karma += val
      @comment_owner.incrementKarmaFromOtherUser(val.to_f,myId)
      #create the comment_grade
      @comment_grade = CommentGrade.new
      @comment_grade.user_id = myId
      @comment_grade.comment_id = comment
      @comment_grade.evaluation = val
      #save user(.karma) and comment_grade
      if @comment_owner.save && @comment_grade.save then
        flash[:notice] = "The comment has been graded"
      end
      
     
   else
     #user already graded comment
     flash[:notice] = "You have already graded that comment"
     
   end 
    
      redirect_to :controller=>"resources"
  end
  
end
